package com.spring.common.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.SperaOSSUtil;
import com.spera.shopoa.util.tools;
import com.spring.common.web.model.MyModel;
import com.spring.common.web.service.CommonService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UDate;
import com.spring.security.filestream.util.TokenUtil;
import com.spring.tools.Result;
import com.spring.tools.ValidatorResultHandler;

@Controller
@RequestMapping(value = "/common")
public class CommonApiController {

	@Resource
	private CommonService commonService;

	/**
	 * 获取所有区域信息
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getServiceIntroduction")
	@ResponseBody
	public Object getServiceIntroduction(String service_type_code,
			String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getServiceIntroduction(service_type_code);

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 获取所有区域信息
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getRegionList")
	@ResponseBody
	public Object applyCard(String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getRegionList();

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 获取子区域信息
	 * 
	 * @param id
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getChildrenRegionList")
	@ResponseBody
	public Object getChildrenRegionList(String id, String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getChildrenRegionList(id);

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 根据区域id获取乐园信息
	 * 
	 * @param id
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getKidsParkList")
	@ResponseBody
	public Object getKidsParkList(String id, String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getKidsParkList(id);

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	@RequestMapping(value = "/getBaseCodeList")
	@ResponseBody
	public Object getBaseCodeList(String type, HttpServletRequest request,
			String callback) {
		List<Map<String, Object>> m = commonService.getDataDictionaryList(type);
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	
	@RequestMapping(value = "/myTest")
	@ResponseBody
	public Object myTest(@Valid MyModel mod,BindingResult result, 
			HttpServletRequest request) {
		Result retVal = ValidatorResultHandler.handle(result);
		return retVal;
	}
	
	@RequestMapping(value = "/myTest2")
	public String myTest2(/*@Valid */MyModel mod, HttpServletRequest request,
			BindingResult result) {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();    
        Validator validator = factory.getValidator();   
        Set<ConstraintViolation<MyModel>> constraintViolations = validator.validate(mod);    
        for (ConstraintViolation<MyModel> constraintViolation : constraintViolations) {    
            System.out.println("对象属性:"+constraintViolation.getPropertyPath());    
            System.out.println("国际化key:"+constraintViolation.getMessageTemplate());    
            System.out.println("错误信息:"+constraintViolation.getMessage());    
        }   
//		Result retVal = ValidatorResultHandler.handle(result);
//        if(!retVal.isSuccess()){
//            System.out.println(JSON.toJSONString(retVal));
//        }
		return "demo/valtest";
	}
	
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param file
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/fileUpload")
//	@ResponseBody
	public Object fileUpload(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "imgFile", required = true) MultipartFile imgFile)
	
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=UTF-8");
		Map<String,Object> m = Maps.newHashMap();
		if(imgFile==null){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请选择上传的文件");
			return m;
		}
		
//		System.out.println(file.getName()+","+);
		String fileType = tools.getFileType(imgFile.getOriginalFilename());
		if(!ApplicationUtils.isNotNull(fileType)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "未知附件类型");
			return m;
		}
		
		
		if(!tools.checkFileType(fileType,"jpg","jpeg","bmp","png")){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "附件类型不允许");
			return m;
		}
		
		String file_token = TokenUtil.generateToken(imgFile.getOriginalFilename(), imgFile.getSize()+"");
		
		try {
			m = new HashMap<String, Object>();
			if (!imgFile.isEmpty()) {
				String newfilename = "kindedit_"+file_token+"_"+imgFile.getOriginalFilename();
				Integer fileSize = 0;
				fileSize = (int) imgFile.getSize() / 1048576;
				
				if (fileSize <= 5) {
					String filePath = SperaOSSUtil.springFileUpOss(AliyunContent.fileBucket,"kindedit_file/"+UDate.getDate()+"/"+newfilename, imgFile);
					m.put("url", filePath);
					m.put("error", "0");
//					m.put("title", "上传成功");
//					m.put(ApplicationUtils.STATUS, "1");
//					m.put(ApplicationUtils.MSG, "上传成功");
				} else {
					m.put("error", "1");
					m.put("message", "上传的文件太大，文件大小不能超过5M");
//					m.put(ApplicationUtils.STATUS, "0");
//					m.put(ApplicationUtils.MSG, "上传的文件太大，文件大小不能超过5M");
					return m;
				}
			} else {
				m.put("error", "1");
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "请选择上传的文件");
				m.put("message", "请选择上传的文件");
			}

		} catch (Exception e) {
			m.put("error", "1");
//			m.put(ApplicationUtils.STATUS, "0");
//			m.put(ApplicationUtils.MSG, "系统异常");
			m.put("message", "系统异常");
			e.printStackTrace();
		}

		return m;
	}
	
}
